import { Component } from "react";
import { Button, Card, Form, Input, message } from "antd";
import styles from './index.module.scss'
import imgSrc from "../../assets/logo.png";
import Checkbox from "antd/lib/checkbox/Checkbox";
import { loginApi } from "../../api/login";

export default class Login extends Component {
  onFinish = async (values) => {
    try {
      const res = await loginApi(values);
      // 保存token值
      localStorage.setItem("token", res.data.token);
      // 跳转到首页
      this.props.history.push("/");
      // 提示用户登录成功
      message.success("用户登录成功");
    } catch (error) {
      if (error.response) {
        // 提示错误信息
        message.warning(error.response.data.message);
      }
    }
  };

  // CSSModule的推荐语法
  // 保留根标签接收重命名,使用:global{非根标签选择器}包住
  // 在JSX中根元素,依旧使用styles.语法访问
  // 其它非根标签,使用字符串的方式访问

  render() {
    return (
      <div className={styles.login}>
        <Card className='login-container'>
          <img src={imgSrc} alt="" className='login-logo' />

          <Form
            onFinish={this.onFinish}
            autoComplete="off"
            initialValues={{
              mobile: "13911111111",
              code: "246810",
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                { required: true, message: "手机号码不能为空" },
                { pattern: /^1[3-9]\d{9}$/, message: "请输入11位手机号码" },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                { required: true, message: "验证码不能为空" },
                { pattern: /^\d{6}$/, message: "请输入6位验证码" },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              valuePropName="checked"
              name="agree"
              rules={[
                {
                  validator: (_, value) => {
                    if (value === true) {
                      return Promise.resolve();
                    } else {
                      return Promise.reject(new Error("请阅读勾选"));
                    }
                  },
                },
              ]}
            >
              <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button block type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
}
